package com.youmans.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youmans.eduservice.entity.EduSubject;
import com.youmans.eduservice.entity.excel.SubjectData;
import com.youmans.eduservice.entity.subject.Subject;
import com.youmans.eduservice.listener.SubjectExcelListener;
import com.youmans.eduservice.mapper.EduSubjectMapper;
import com.youmans.eduservice.service.EduSubjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author Youmans
 * @since 2022-05-06
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {
    @Override
    public void saveSubject(MultipartFile file,EduSubjectService subjectService) {
        try {
            //文件输入流
            InputStream inputStream = file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(inputStream, SubjectData.class,new SubjectExcelListener(subjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public List<Subject> getAllSubject() {


        //    1    查询所有分类
        List<EduSubject> entities = baseMapper.selectList(null);

//        2    组装成父子的树形结构
//            2.1 找到所有的一级分类
        List<Subject> list = new ArrayList<>() ;
        for (EduSubject entity : entities) {
            Subject s = new Subject();
            BeanUtils.copyProperties(entity,s);
            list.add(s) ;
        }
        //获取父节点
        List<Subject> collect = list.stream().filter(m ->
                m.getParentId().equals("0")
        ).map(
                (m) -> {
                    m.setChildren(getChildrens(m, list));
                    return m;
                }
        ).collect(Collectors.toList());
        return collect;
    }
    /**
     * 递归查询子节点
     * @param root  根节点
     * @param all   所有节点
     * @return 根节点信息
     */
    private List<Subject> getChildrens(Subject root, List<Subject> all) {
        List<Subject> children = all.stream().filter(m -> {
            return Objects.equals(m.getParentId(), root.getId());
        }).map(
                (m) -> {
                    m.setChildren(getChildrens(m, all));
                    return m;
                }
        ).collect(Collectors.toList());
        return children;
    }


}
